package alg.leetcode;

/**
 * 链表相加
 * @author xujian
 * @date 2021-07-03 10:27
 **/
public class No61 {
     class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     }
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
         ListNode ret = new ListNode();
         ListNode res = ret;
         ListNode t1 = l1;
         ListNode t2 = l2;
         int carry = 0;
         while (t1 != null || t2 !=null) {
             int a = t1 != null ? t1.val : 0;
             int b = t2 != null ? t2.val : 0;
             int c = a + b + carry;
             if (c > 9) {
                 res.next = new ListNode(c % 10);
             } else {
                 res.next = new ListNode(c);
             }
             carry = c / 10;
             if (t1 != null) {
                 t1 = t1.next;
             }
             if (t2 != null) {
                 t2 = t2.next;
             }
             res = res.next;
         }
         if (carry == 1) {
             res.next = new ListNode(1);
         }
         return ret.next;
    }
}
